package com.innovation.ic.b1b.framework.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * redis操作的具体实现类
 */
public class RedisManager {

    private RedisTemplate<String, String> redisTemplate;

    public RedisManager(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void set(String key, String value, long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除一条记录
     *
     * @param key
     * @return
     */
    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 批量删除
     *
     * @param keys
     * @return
     */
    public Long del(List<String> keys) {
        return redisTemplate.delete(keys);
    }

    /**
     * 批量删除
     *
     * @param keys
     * @return
     */
    public Long del(Set<String> keys) {
        return redisTemplate.delete(keys);
    }

    /**
     * 模糊查询key的值
     *
     * @param key 模糊查询的key
     * @return 返回查询结果
     */
    public List<String> keysFuzzy(String key) {
        Set<String> keys = redisTemplate.keys(key);
        if (keys != null && keys.size() > 0) {
            return redisTemplate.opsForValue().multiGet(keys);
        }
        return new ArrayList<>();
    }

    /**
     * 查询多个key的值
     *
     * @param keys 要查询的id值的集合
     * @return 返回查询结果
     */
    public List<String> getList(List<String> keys) {
        if (keys != null && keys.size() > 0) {
            return redisTemplate.opsForValue().multiGet(keys);
        }
        return new ArrayList<>();
    }

    /**
     * 模糊查询，匹配key的前缀
     *
     * @param keyPrefix
     * @return
     */
    public Set<String> keysPrefix(String keyPrefix) {
        return redisTemplate.keys(keyPrefix + "*");
    }

    /**
     * 设置过期时间
     *
     * @param key
     * @param time
     * @return
     */
    public Boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public synchronized Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    public Boolean hSet(String key, String hashKey, Object value, long time) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return expire(key, time);
    }

    public void hSet(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    public Boolean hSetAll(String key, Map<String, Object> map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        return expire(key, time);
    }

    public void hSetAll(String key, Map<String, ?> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    public void hDel(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    public Boolean hHasKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    public Long hIncr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }

    public Long hDecr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }

    public Set<String> sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    public Long sAdd(String key, String... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    public Long sAdd(String key, long time, String... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        expire(key, time);
        return count;
    }

    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    /**
     * 获取redis获取数据分页形式返回
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<String> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    public Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    public Long lPush(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    public Long lPush(String key, String value, long time) {
        Long index = redisTemplate.opsForList().rightPush(key, value);
        expire(key, time);
        return index;
    }

    public Long lPushAll(String key, String... values) {
        return redisTemplate.opsForList().rightPushAll(key, values);
    }

    public Long lPushAll(String key, Long time, String... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        expire(key, time);
        return count;
    }


//    public void listAdd(String key, String[] data) {
//        redisTemplate.opsForList().rightPushAll(key, data);
//    }

    public void lPushAll(String key, List data) {
        if (data != null && data.size() > 0) {
            String[] resultSize = new String[data.size()];
            for (int i = 0; i < data.size(); i++) {
                String resultData = JSON.toJSONString(data.get(i), SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                resultSize[i] = resultData;
            }
            this.lPushAll(key, resultSize);
        }
    }

    public Long lRemove(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(key, count, value);
    }

    public Boolean bitAdd(String key, int offset, boolean b) {
        return redisTemplate.opsForValue().setBit(key, offset, b);
    }

    public Boolean bitGet(String key, int offset) {
        return redisTemplate.opsForValue().getBit(key, offset);
    }

    public Long bitCount(String key) {
        return redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount(key.getBytes()));
    }

    public List<Long> bitField(String key, int limit, int offset) {
        return redisTemplate.execute((RedisCallback<List<Long>>) con ->
                con.bitField(key.getBytes(),
                        BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(limit)).valueAt(offset)));
    }

    public byte[] bitGetAll(String key) {
        return redisTemplate.execute((RedisCallback<byte[]>) con -> con.get(key.getBytes()));
    }

    public Long geoAdd(String key, Double x, Double y, String name) {
        return redisTemplate.opsForGeo().add(key, new Point(x, y), name);
    }

    public List<Point> geoGetPointList(String key, String... place) {
        return redisTemplate.opsForGeo().position(key, place);
    }

    public Distance geoCalculationDistance(String key, String placeOne, String placeTow) {
        return redisTemplate.opsForGeo()
                .distance(key, placeOne, placeTow, RedisGeoCommands.DistanceUnit.KILOMETERS);
    }

    public GeoResults<RedisGeoCommands.GeoLocation<String>> geoNearByPlace(String key, String place, Distance distance, long limit, Sort.Direction sort) {
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates();
        // 判断排序方式
        if (Sort.Direction.ASC == sort) {
            args.sortAscending();
        } else {
            args.sortDescending();
        }
        args.limit(limit);
        return redisTemplate.opsForGeo()
                .radius(key, place, distance, args);
    }

    public List<String> geoGetHash(String key, String... place) {
        return redisTemplate.opsForGeo()
                .hash(key, place);
    }

    /**--------------------------- zSet相关操作 --------------------------------*/

    /**
     * 添加元素，有序集合是按照元素的score值由小到大排列
     *
     * @param key
     * @param value
     * @param score
     * @return
     */
    public Boolean zAdd(String key, String value, double score) {
        return redisTemplate.opsForZSet().add(key, value, score);
    }

    /**
     * 添加元素
     *
     * @param key
     * @param values
     * @return
     */
    public Long zAdd(String key, Set<ZSetOperations.TypedTuple<String>> values) {
        return redisTemplate.opsForZSet().add(key, values);
    }

    /**
     * @param key
     * @param values
     * @return
     */
    public Long zRemove(String key, Object... values) {
        return redisTemplate.opsForZSet().remove(key, values);
    }

    /**
     * 增加元素的score值，并返回增加后的值
     *
     * @param key
     * @param value
     * @param delta
     * @return
     */
    public Double zIncrementScore(String key, String value, double delta) {
        return redisTemplate.opsForZSet().incrementScore(key, value, delta);
    }

    /**
     * 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列
     *
     * @param key
     * @param value
     * @return 0表示第一位
     */
    public Long zRank(String key, Object value) {
        return redisTemplate.opsForZSet().rank(key, value);
    }

    /**
     * 返回元素在集合的排名,按元素的score值由大到小排列
     *
     * @param key
     * @param value
     * @return
     */
    public Long zReverseRank(String key, Object value) {
        return redisTemplate.opsForZSet().reverseRank(key, value);
    }

    /**
     * 分页显示, 升序排列
     *
     * @param key
     * @param startIndex 开始位置索引，从0开始
     * @param endIndex   结束位置索引, -1查询所有
     * @return
     */
    public Set<String> zRange(String key, long startIndex, long endIndex) {
        return redisTemplate.opsForZSet().range(key, startIndex, endIndex);
    }

    /**
     * 分页显示, 降序排列，并且把score值也获取
     *
     * @param key
     * @param startIndex
     * @param endIndex
     * @return
     */
    public Set<ZSetOperations.TypedTuple<String>> zRangeWithScores(String key, long startIndex,
                                                                   long endIndex) {
        return redisTemplate.opsForZSet().rangeWithScores(key, startIndex, endIndex);
    }

    /**
     * 根据Score值查询集合元素, 从小到大排序。参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE
     *
     * @param key
     * @param minScore 最小值
     * @param maxScore 最大值
     * @return
     */
    public Set<String> zRangeByScore(String key, double minScore, double maxScore) {
        return redisTemplate.opsForZSet().rangeByScore(key, minScore, maxScore);
    }

    /**
     * 根据Score值查询集合元素, 从小到大排序，并且返回score。
     * 参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE
     *
     * @param key
     * @param minScore 最小值
     * @param maxScore 最大值
     * @return
     */
    public Set<ZSetOperations.TypedTuple<String>> zRangeByScoreWithScores(String key,
                                                                          double minScore, double maxScore) {
        return redisTemplate.opsForZSet().rangeByScoreWithScores(key, minScore, maxScore);
    }

    /**
     * 分页显示，查找score在minScore和maxScore范围内，根据score升序排列，并返回score。
     * 参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE。参数count是返回的记录数
     *
     * @param key
     * @param minScore
     * @param maxScore
     * @param startIndex
     * @param count
     * @return
     */
    public Set<ZSetOperations.TypedTuple<String>> zRangeByScoreWithScores(String key,
                                                                          double minScore, double maxScore, long startIndex, long count) {
        return redisTemplate.opsForZSet().rangeByScoreWithScores(key, minScore, maxScore,
                startIndex, count);
    }

    /**
     * 分页显示，降序排列
     *
     * @param key
     * @param startIndex 开始位置索引，从0开始
     * @param endIndex   结束位置索引, -1查询所有
     */
    public Set<String> zReverseRange(String key, long startIndex, long endIndex) {
        return redisTemplate.opsForZSet().reverseRange(key, startIndex, endIndex);
    }

    /**
     * 分页显示，降序排列，返回score
     *
     * @param key
     * @param startIndex
     * @param endIndex
     * @return
     */
    public Set<ZSetOperations.TypedTuple<String>> zReverseRangeWithScores(String key,
                                                                          long startIndex, long endIndex) {
        return redisTemplate.opsForZSet().reverseRangeWithScores(key, startIndex,
                endIndex);
    }

    /**
     * 分页显示，查询score列在minScore和maxScore之间的集合元素（包括minScore和maxScore）, 降序排列。
     * 参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE
     *
     * @param key
     * @param minScore
     * @param maxScore
     * @return
     */
    public Set<String> zReverseRangeByScore(String key, double minScore,
                                            double maxScore) {
        return redisTemplate.opsForZSet().reverseRangeByScore(key, minScore, maxScore);
    }

    /**
     * 根据Score值查询集合元素（范围是score在minScore和maxScore之间）, 降序排列，并返回score。
     * 参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE
     *
     * @param key
     * @param minScore
     * @param maxScore
     * @return
     */
    public Set<ZSetOperations.TypedTuple<String>> zReverseRangeByScoreWithScores(
            String key, double minScore, double maxScore) {
        return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
                minScore, maxScore);
    }

    /**
     * 分页显示，score在minScore和maxScore范围内，降序排列。
     * 参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE。参数count是返回的记录数
     *
     * @param key        redis中的key
     * @param minScore   score的最小值
     * @param maxScore   score的最大值
     * @param startIndex 指定位置
     * @param count   获取元素的数量
     * @return
     */
    public Set<String> zReverseRangeByScore(String key, double minScore, double maxScore, long startIndex, long count) {
        return redisTemplate.opsForZSet().reverseRangeByScore(key, minScore, maxScore, startIndex, count);
    }

    /**
     * 根据score值获取集合元素数量（范围是score在minScore和maxScore之间）。参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE
     *
     * @param key
     * @param minScore
     * @param maxScore
     * @return
     */
    public Long zCount(String key, double minScore, double maxScore) {
        return redisTemplate.opsForZSet().count(key, minScore, maxScore);
    }

    /**
     * 获取集合大小
     *
     * @param key
     * @return
     */
    public Long zSize(String key) {
        return redisTemplate.opsForZSet().size(key);
    }

    /**
     * 获取集合大小
     *
     * @param key
     * @return
     */
    public Long zZCard(String key) {
        return redisTemplate.opsForZSet().zCard(key);
    }

    /**
     * 获取集合中value元素的score值
     *
     * @param key
     * @param value
     * @return
     */
    public Double zScore(String key, Object value) {
        return redisTemplate.opsForZSet().score(key, value);
    }

    /**
     * 移除指定索引位置的成员。startIndex是开始位置的索引，endIndex是结束位置的索引
     *
     * @param key
     * @param startIndex
     * @param endIndex
     * @return
     */
    public Long zRemoveRange(String key, long startIndex, long endIndex) {
        return redisTemplate.opsForZSet().removeRange(key, startIndex, endIndex);
    }

    /**
     * 根据指定的score值的范围来移除成员（范围是score在minScore和maxScore之间）。
     * 参数min可以为1，也可以为Long.MIN_VALUE，但是不能是0；参数max可以为long.MAX_VALUE
     *
     * @param key
     * @param minScore
     * @param maxScore
     * @return
     */
    public Long zRemoveRangeByScore(String key, double minScore, double maxScore) {
        return redisTemplate.opsForZSet().removeRangeByScore(key, minScore, maxScore);
    }

    /**
     * 获取key和otherKey的并集并存储在destKey中
     *
     * @param key
     * @param otherKey
     * @param destKey
     * @return
     */
    public Long zUnionAndStore(String key, String otherKey, String destKey) {
        return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
    }

    /**
     * @param key
     * @param otherKeys
     * @param destKey
     * @return
     */
    public Long zUnionAndStore(String key, Collection<String> otherKeys,
                               String destKey) {
        return redisTemplate.opsForZSet()
                .unionAndStore(key, otherKeys, destKey);
    }

    /**
     * 交集
     *
     * @param key
     * @param otherKey
     * @param destKey
     * @return
     */
    public Long zIntersectAndStore(String key, String otherKey,
                                   String destKey) {
        return redisTemplate.opsForZSet().intersectAndStore(key, otherKey,
                destKey);
    }

    /**
     * 交集
     *
     * @param key
     * @param otherKeys
     * @param destKey
     * @return
     */
    public Long zIntersectAndStore(String key, Collection<String> otherKeys,
                                   String destKey) {
        return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
                destKey);
    }

    /**
     * 根据redis的key的前缀删除对应数据
     *
     * @param redisKeyPrefix redisKeyPrefix
     * @return 返回删除结果
     */
    public Boolean delRedisDataByKeyPrefix(String redisKeyPrefix) {
        Set<String> keySet = keysPrefix(redisKeyPrefix);
        Long del = del(keySet);
        if (del > 0) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

    /**
     * @param key
     * @param options
     * @return
     */
    public Cursor<ZSetOperations.TypedTuple<String>> zScan(String key, ScanOptions options) {
        return redisTemplate.opsForZSet().scan(key, options);
    }

    public List page(String key, String pattern) {
        Cursor<ZSetOperations.TypedTuple<String>> cursor = redisTemplate.opsForZSet().scan(key,
                ScanOptions.scanOptions().match(pattern).count(Integer.MAX_VALUE).build());
        List list = new ArrayList();
        while (cursor.hasNext()) {
            ZSetOperations.TypedTuple<String> typedTuple = cursor.next();
            Object score = typedTuple.getScore();
            String value = typedTuple.getValue();
            list.add(value);
        }
        cursor.close();
        return list;
    }

    /**
     * zset 排序模糊查询
     *
     * @param key
     * @param pattern 模糊匹配规则
     * @param isDesc  true按score降序 false按score升序
     * @return
     */
    public List pageSort(String key, String pattern, Boolean isDesc) {
        Cursor<ZSetOperations.TypedTuple<String>> cursor = redisTemplate.opsForZSet().scan(key,
                ScanOptions.scanOptions().match(pattern).count(Integer.MAX_VALUE).build());
        List list = new ArrayList();
        HashMap<String, Double> map = new HashMap<>();
        while (cursor.hasNext()) {
            ZSetOperations.TypedTuple<String> typedTuple = cursor.next();
            double score = typedTuple.getScore();
            String value = typedTuple.getValue();
            map.put(value, score);
        }
        //排序
        List<Map.Entry<String, Double>> lstEntry = new ArrayList<>(map.entrySet());
        //判断是升序还是降序
        if (isDesc) {
            Collections.sort(lstEntry, ((o1, o2) -> {
                return o1.getValue().compareTo(o2.getValue());
            }));
        } else {
            Collections.sort(lstEntry, ((o1, o2) -> {
                return o2.getValue().compareTo(o1.getValue());
            }));
        }

        //添加到list
        lstEntry.forEach(o -> {
            list.add(o.getKey());
        });
        cursor.close();
        return list;
    }

    /**
     * 获取RedisConnectionFactory类
     *
     * @return
     */
    public RedisConnectionFactory getConnectionFactory() {
        return redisTemplate.getConnectionFactory();
    }


}